package edu.nuc.ahm.juc.bq;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/*
* 阻塞队列
* */
public class BlockQueueTest {
    public static void main(String[] args) throws InterruptedException {
        test3();
    }
    /*
    * 抛出异常   Queue full  NoSuchElementException b
    * */
    public static void test1(){
        // 队列的大小
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
        // 添加
        System.out.println( blockingQueue.add("a"));
        System.out.println( blockingQueue.add("b"));
        System.out.println( blockingQueue.add("c"));
        System.out.println( blockingQueue.add("d"));
        // 移除
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        // 查看队首的元素


    }

/*
*
* 不抛出异常
*
* */
    public static void test2(){
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("b"));
        System.out.println(blockingQueue.offer("c"));
        System.out.println(blockingQueue.offer("d"));

        System.out.println("====================");
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll()); //null
    }

    /*
    *
    * 等待 ，阻塞 （一直阻塞）
    * */
    public static void test3() throws InterruptedException {

        // 队列的大小
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
        // 一直阻塞
        blockingQueue.put("a");
        blockingQueue.put("b");
        blockingQueue.put("c");
        // 队列已经没有位置了 一直阻塞
//        blockingQueue.put("d");
        // 出来
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        // 没有元素了 还在等待取出来
        System.out.println(blockingQueue.take());


    }
    public static void test4() throws InterruptedException {

        // 队列的大小
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
        // 一直阻塞
        blockingQueue.offer("a");
        blockingQueue.offer("b");
        blockingQueue.offer("c");
        // 队列已经没有位置了   超时就退出
        blockingQueue.offer("d", 2,TimeUnit.SECONDS);
        // 出来
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        // 没有元素了 还在等待取出来
        System.out.println(blockingQueue.take());


    }

}
